package com.wongoing.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * 类功能说明 TODO:常用常量定义 类修改者 修改日期 修改说明
 * 
 * @author yuany yuany@mesnac.com
 * @date 2016-5-20 17:21:14
 * @version V1.0
 */

public class Constants {
	
	// mybatis 删除方法名定义 start
	public static final String SYSLOGNAMESPACE = "com.wongoing.sys.model.SysLog";
	public static final String DELETEBYWHERE = ".deleteByWhere";// 参数为where,类型为String
	public static final String DELETEBYPARAM = ".deleteByParam";// 参数为map<String,Object>
	public static final String DELETEBYPRIMARYKEYS = ".deleteByPrimaryKeys";// 参数为map<String,Object>
	public static final String DELETEBYPRIMARYKEY = ".deleteByPrimaryKey";// 按主键删除，参数为Serializable
	// mybatis 删除方法名定义 end
	public static final String LOGIN_SESSION_DATANAME = "users";
	public static final String LOGIN_URL = "login";
	public static final String LOGIN_SUCCESS_URL = "index";
	public static final String LOGIN_LOGIN_OUT_URL = "loginout";
	public static final String LOGIN_MSG = "loginMsg";
	public static final String USERNAME_IS_NULL = "用户名为空!";
	public static final String LOGIN_IS_EXIST = "该用户已登录!";
	public static final String UNKNOWN_SESSION_EXCEPTION = "异常会话!";
	public static final String UNKNOWN_ACCOUNT_EXCEPTION = "账号错误!";
	public static final String INCORRECT_CREDENTIALS_EXCEPTION = "密码错误!";
	public static final String LOCKED_ACCOUNT_EXCEPTION = "账号已被锁定，请与系统管理员联系!";
	public static final String INCORRECT_CAPTCHA_EXCEPTION = "验证码错误!";
	public static final String AUTHENTICATION_EXCEPTION = "您没有授权!";
	public static final String UNKNOWN_EXCEPTION = "出现未知异常,请与系统管理员联系!";
	public static final String UNKNOWN_EXCEPTION_TO_RESET = "出现未知异常,请重新尝试或重新登录后尝试!";
	public static final String SIGN_IN_EXCEPTION = "账号已登录，请误重复登录!";
	public static final String SIGN_IN_ABNORMAL = "账户登录异常，请重新登录!";
	public static final String SIGN_NO = "您的账户未登录或已登录超时，为了您的账户安全，请重新登录!";
	public static final String PASSWORD_RESET_OK = "密码修改成功!";
	public static final String OLD_PASSWORD_WRONG = "您输入的旧密码错误，请重新输入!";
	public static final String REPEAT_LOGIN_EXCEPTION = "repeatLogin";
	public static final String TREE_GRID_ADD_STATUS = "add";
	public static final String POST_DATA_SUCCESS = "数据更新成功!";
	public static final String POST_DATA_FAIL = "提交失败了!";
	public static final String GET_SQL_LIKE = "%";
	public static final String IS_FUNCTION = "F";
	public static final String PERSISTENCE_ENABLE_STATUS = "0";// 启用
	public static final String PERSISTENCE_DELETE_STATUS = "1";// 删除
	public static final String PERSISTENCE_FROZEN_STATUS = "2";// 冻结
	public static final String PERSISTENCE_DISABLE_STATUS = "3";// 停用
	public static final String SYSTEM_ADMINISTRATOR = "admin";
	public static final String SYSTEM_USER = "user";
	public static final String NULL_STRING = "";
	public static final String IS_DOT = ".";
	public static final String HQL_LIKE = "like";
	public static final String TEXT_TYPE_PLAIN = "text/plain";
	public static final String TEXT_TYPE_HTML = "text/html";
	public static final String FUNCTION_TYPE_O = "O";
	public static final String TREE_STATUS_OPEN = "open";
	public static final String TREE_STATUS_CLOSED = "closed";
	public static final String IS_EXT_SUBMENU = " 或可能包含菜单!";

	public static final String SHIRO_GUEST= "shiroGuest";
	public static final String LOGS_INSERT = "insert:";
	public static final String LOGS_INSERT_TEXT = "插入:";
	public static final String LOGS_INSERT_NAME = "insertLogs";
	public static final String LOGS_UPDATE = "UPDATE";
	public static final String LOGS_UPDATE_TEXT = "更新:";
	public static final String LOGS_UPDATE_NAME = "updateLogs";
	public static final String LOGS_DELETE = "DELETE";
	public static final String LOGS_DELETE_TEXT = "删除:";
	public static final String LOGS_DELETE_NAME = "deleteLogs";
	public static final String LOGS_LOGIN = "LOGIN";
	public static final String LOGS_LOGIN_TEXT = "登录:";
	public static final String LOGS_LOGIN_NAME = "loginLogs:";
	public static final String LOGS_TB_NAME = "Log";
	public static final String FILE_SUFFIX_SQL = ".sql";
	public static final String FILE_SUFFIX_ZIP = ".zip";
	public static final String MATERIAL_TYPE = "MaterialType";
	public static final Integer MAX_LIMIT = 20;
	
	//所有数据库中status的状态
	public static final String STATUS_NORMAL = "0";//已激活、正常
	public static final String STATUS_INCEPTION = "1";//未激活、删除
	public static final String STATUS_DISABLE = "3";//注销、停用 
	public static final String STATUS_FROZEN = "4";//锁定、冻结
	
	//系统存储图片的具体文件夹名称
	public static final String UPLOAD_IMG_AD = "ad";
	public static final String UPLOAD_IMG_CAR = "car";
	public static final String UPLOAD_IMG_CARLOGO = "carLogo";
	public static final String UPLOAD_IMG_EVALUATE = "evaluate";
	public static final String UPLOAD_IMG_REFUND = "refund";
	public static final String UPLOAD_IMG_RESTROOM = "restroom";
	public static final String UPLOAD_IMG_SLIDER = "slider";
	public static final String UPLOAD_IMG_CAV_SLIDER = "cavSlider";
	public static final String UPLOAD_IMG_LOCATION= "location";
	public static final String UPLOAD_IMG_USER = "user";
	public static final String UPLOAD_IMG_ITEM = "item";
	public static final String UPLOAD_IMG_SITE= "site";
	public static final String UPLOAD_IMG_COLUMN= "column";
	public static final String UPLOAD_IMG_USERAVATAR= "userAvatar";
	public static final String UPLOAD_IMG_SHARE= "share";
	public static final String UPLOAD_IMG_ARTICLE= "article";
	public static final String UPLOAD_IMG_ESSAY= "essay";
	public static final String UPLOAD_IMG_DISCOVERY= "discovery";
	public static final Integer IS_NOT_BOOK = 0;// 未订阅
	public static final Integer IS_BOOK = 1;// 已订阅
	public static final String ACQUIESCE_FTY_NAME = "默认工厂（请修改）";
	public static final String ACQUIESCE_POST_NAME = "默认岗位（请修改）";

	/** 报警推送标识begin */
	public static final Integer PUSH_ALARM_CONCENTRATOR = 1; // 集中器离线超时报警
	public static final Integer PUSH_ALARM_ELECTRIC = 2; // 电报警
	public static final Integer PUSH_ALARM_STREAM = 3; // 气报警
	public static final Integer PUSH_ALARM_SYSTEM = 4; // 系统报警
	/** 报警推送标识end */

	/** 能源类型begin */
	public static final Integer ENERGYTYPE_ELECTRIC = 2; // 能源類型-电
	public static final Integer ENERGYTYPE_STREAM = 3; // 能源类型-气
	/** 能源类型end */

	public static final String TRANSLATE_LANGUAGE_ZH = "zh";// 翻译语言-中文
	public static final String TRANSLATE_LANGUAGE_EN = "en";// 翻译语言-英语
	public static final String TRANSLATE_ZH_ALL = "全部";
	public static final String TRANSLATE_EN_ALL = "All";

	/** 日月年报表编号begin */
	// 0：日报表;1:月报表；2:年报表
	public static final int DAILY_REPORT = 0;
	public static final int MONTH_REPORT = 1;
	public static final int YEAR_REPORT = 2;
	public static final int NO_TOTAL_FLAG = -1;// 非总数据（数据详情的标志）

	/** 日月年报表编号end */

	public static final String ERROR = "ERROR";
	

	//用户账户规则：字母开头，5-16位，允许字母数字下划线
	public static final String REX_ACCOUNT = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$";
	//正则表达式（密码）:6-20位，至少包含数字、字母或特殊字符中的两种组合
	public static final String REX_PWD = "(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,20}$";
	//邮箱正则表达式
	public static final String REX_EMAIL = "(^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$)";
	//手机号验证规则
	public static final String REX_PHONE = "^1(3|4|5|7|8)\\d{9}$";
	//定时任务静态常量
	public static final String QUARTZ_JOB_AUTORUN = "0";
	public static final String QUARTZ_JOB_UNAUTORUN = "1";
	
	// ajax return code ： success
	public static int RETURN_CODE_SUCCESS = 0;
	public static String RETURN_DEFAULT_MSG_SUCCESS = "成功";
	// ajax return code ： error
	public static int RETURN_CODE_ERROR = -1;
	public static String RETURN_DEFAULT_MSG_ERROR = "失败";
		
	
    
	/**
	 * 函数功能说明 TODO:获取UUID生成的主键
	 * 
	 * @author yuany yuany@mesnac.com @date 2016-5-20 17:21:14 @Title:
	 * getPrimaryKeyByUUID @param @return 设定文件 @return String 返回类型 @throws
	 */
	public static String getPrimaryKeyByUUID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 函数功能说明 TODO:获取当前登录用户实体类
	 * 
	 * @author yuany yuany@mesnac.com @date 2016-5-20 17:21:14 修改内容 @Title:
	 * getCurrendUser @Description: TODO: @param @return 设定文件 @return Users
	 * 返回类型 @throws
	 */
	// public static ShiroUser getCurrendUser(){
	// Subject subject=SecurityUtils.getSubject();
	// return (ShiroUser)subject.getSession().getAttribute(SHIRO_USER);
	// }

	/**
	 * 函数功能说明 TODO:获得简单查询条件
	 * 
	 * @author yuany yuany@mesnac.com @date 2016-5-20 17:21:14 修改内容 @Title:
	 * getSearchConditionsHQL @Description: @param @param asName @param @param
	 * param @param @return 设定文件 @return String 返回类型 @throws
	 */
	public static String getSearchConditionsHQL(String asName, Map<String, Object> param) {
		StringBuffer sb = new StringBuffer();
		if (param != null && !param.isEmpty()) {
			for (String name : param.keySet()) {
				String paramName = name;
				if (paramName.indexOf(".") > -1) {
					paramName = paramName.substring(paramName.indexOf('.') + 1);
				}
				sb.append(" and " + asName + Constants.IS_DOT + name + " like :" + paramName + "");
			}
		}
		return sb.toString();
	}

	/**
	 * 函数功能说明 TODO:获得简单查询条件
	 * 
	 * @author yuany yuany@mesnac.com @date 2016-5-20 17:21:14 修改内容 @Title:
	 * getSearchConditionsHQL @Description: @param @param asName @param @param
	 * param @param @return 设定文件 @return String 返回类型 @throws
	 */
	public static String getSearchConditionsSQL(String asName, Map<String, Object> param) {
		StringBuffer sb = new StringBuffer();
		if (param != null && !param.isEmpty()) {
			for (String name : param.keySet()) {
				if (name.indexOf('.') != -1) {
					sb.append(" and " + name + " like '" + param.get(name) + "' ");
				} else {
					sb.append(" and " + asName + Constants.IS_DOT + name + " like '" + param.get(name) + "' ");
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 函数功能说明 TODO:获得简单查询条件
	 * 
	 * @author yuany yuany@mesnac.com @date 2016-5-20 17:21:14 修改内容 @Title:
	 * getSearchConditionsHQL @Description: @param @param asName @param @param
	 * param @param @return 设定文件 @return String 返回类型 @throws
	 */
	public static String getOrderAndLimitConditionsSQL(String orderby, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		String limit = " limit " + ((page - 1) * rows) + "," + 10 + " ";
		return orderby + limit;
	}

	/**
	 * 函数功能说明 TODO:获取客户端ip地址 @author yuany yuany@mesnac.com @date 2016-5-20
	 * 17:21:14 @Title: getIpAddr @Description: @param @return 设定文件 @return String
	 * 返回类型 @throws
	 */
	public static String getIpAddr() {
		String ip = "";
		try {
			Subject subject = SecurityUtils.getSubject();
			ip = subject.getSession().getHost();
		} catch (Exception e) {
			ip = "APP调用";
		}
		return ip;
	}

	public static String[] getFiledName(Object o) {
		try {
			Field[] fields = o.getClass().getDeclaredFields();
			String[] fieldNames = new String[fields.length];
			for (int i = 0; i < fields.length; i++) {
				fieldNames[i] = fields[i].getName();
			}
			return fieldNames;
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			System.out.println("属性不存在");
			return "";
		}
	}
	
	public static HashMap<String, Method> ConverBean(Class<?> drbean) {
		Class<?> stopClass = null;
		// 存放class信息
		BeanInfo drbeaninfo = null;
		// 存放属性信息
		PropertyDescriptor[] props;
		HashMap<String, Method> map = new HashMap<String, Method>();
		try {
			// 获取class中得属性方法信息
			drbeaninfo = Introspector.getBeanInfo(drbean, stopClass);
			// 把class中属性放入PropertyDescriptor数组中
			props = drbeaninfo.getPropertyDescriptors();
			for (int i = 0; i < props.length; i++) {
				// 获取属性所对应的set方法
				Method setMethod = props[i].getWriteMethod();
				// 判断属性是否有set方法 如果有放入map<属性名，set方法>中
				if (setMethod != null) {
					String field = props[i].getName().toLowerCase();
					map.put(field, setMethod);
				}
			}
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	private static final int BUFFER_SIZE = 16 * 1024;

	public static void copy(File src, String fullSavePath) {
		InputStream in = null;
		OutputStream out = null;
		File newFile = new File(fullSavePath);
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(newFile), BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String BASE_PATH = System.getProperty("Archimedes");

	public static String dbBackUp() {
		// 生成临时备份文件
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
		String fineName = "dbBackUp-" + sd.format(new Date());
		String sqlName = fineName + Constants.FILE_SUFFIX_SQL;
		String pathSql = BASE_PATH + "attachment" + File.separator + "dbBackUp";
		try {
			File filePathSql = new File(pathSql);
			if (!filePathSql.exists()) {
				filePathSql.mkdir();
			}
			StringBuffer sbs = new StringBuffer();
			sbs.append("mysqldump ");
			sbs.append("-h 192.168.110.10 ");
			sbs.append("--user=root");
			sbs.append(" --password=fortune123");
			sbs.append(" --lock-all-tables=true ");
			sbs.append("--result-file=" + pathSql + File.separator);
			sbs.append(sqlName + " ");
			sbs.append(" --default-character-set=utf8 ");
			sbs.append("Archimedes");
			Runtime runtime = Runtime.getRuntime();
			Process child = runtime.exec(sbs.toString());
			// 读取备份数据并生成临时文件
			InputStream in = child.getInputStream();
			OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(pathSql), "utf8");
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8"));
			String line = reader.readLine();
			while (line != null) {
				writer.write(line + "\n");
				line = reader.readLine();
			}
			writer.flush();
		} catch (Exception e) {

		}
		return sqlName;
	}
}
